﻿using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Model;
using AgencyManagerSystem.AsmType;
using System;
using System.IO;
using System.Text.RegularExpressions;

namespace AgencyManagerSystem.Core
{
    public class OrderFileManager
    {
        PicUpdater picUpdater = new PicUpdater(new PicFetcher());
        public AsmObject<PicModel> CreateFileForOrder(string webroot,string fileInBase64,int ownerid)
        {
            PicModel picModel = new PicModel();
            picModel.Type = 1;
            picModel.Owner = ownerid;
            picModel.PicCode = ownerid +"_"+ DateTime.Now.ToString("yyMMddHHmmss") +"_"+ fileInBase64.GetHashCode().ToString();
            try
            {
                string msg;
                string uploadpath = webroot + "/upload/" ;
                var match = Regex.Match(fileInBase64, "data:image/jpeg;base64,([\\w\\W]*)$");
                if (match.Success)
                {
                    fileInBase64 = match.Groups[1].Value;
                }
                byte[] pic = Convert.FromBase64String(fileInBase64);
                if(!File.Exists(uploadpath))
                {
                    Directory.CreateDirectory(uploadpath);
                }
                File.WriteAllBytes(uploadpath+picModel.PicCode+".jpg", pic);
                Util.CreateThumbnail(uploadpath + picModel.PicCode + "_thumb.jpg",pic);
                picUpdater.Save(picModel, out msg);
                return new AsmObject<PicModel>() { Data = picModel, Message = "上传成功", Result = AmsCode.Succ };
            }
            catch(Exception ex)
            {
                return new AsmObject<PicModel>() { Data = null, Message = ex.Message, Result = AmsCode.InnError };
            }
        }
        public bool ChangeOwner(int[] idList,int owner)
        {
            return picUpdater.BulkUpdate(idList,owner);
        }
        public bool Delete(int id)
        {
            string message;
            return picUpdater.Delete(id,out message);
        }
    }
}
